import React, { useState, useEffect } from 'react';
import { Card, List, Tag, Space, Typography, Spin, message, Button, Statistic, Row, Col } from 'antd';
import { DownloadOutlined, EyeOutlined, UserOutlined, ClockCircleOutlined, ArrowUpOutlined, ArrowDownOutlined, LikeOutlined, DatabaseOutlined } from '@ant-design/icons';
import { torrents } from '../services';

const { Title, Text } = Typography;

const AllTorrents = () => {
  const [torrentsList, setTorrentsList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);

  useEffect(() => {
    loadAllTorrents();
  }, []);

  const loadAllTorrents = async () => {
    try {
      setLoading(true);
      setError(null);

      const response = await torrents.getAllUploadedTorrents();

      if (response.success) {
        setTorrentsList(response.data.torrents || []);
        message.success(`成功加载 ${response.data.total || 0} 个种子`);
      } else {
        throw new Error(response.message || '获取种子列表失败');
      }
    } catch (err) {
      console.error('加载种子列表失败:', err);
      setError(err.message);
      message.error(`加载失败: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  const handleDownload = async (torrent) => {
    try {
      if (torrent.tResource && torrent.id) {
        // 确保传递种子ID给后端用于记录下载次数
        await torrents.downloadTorrent(torrent.tResource, torrent.id);
        message.success('种子文件下载成功');
      } else {
        message.warning('种子文件路径或ID不存在');
      }
    } catch (error) {
      console.error('下载失败:', error);
      message.error('下载失败: ' + error.message);
    }
  };

  const formatFileSize = (size) => {
    if (!size) return '未知大小';
    if (typeof size === 'string') return size;

    const bytes = parseFloat(size);
    if (isNaN(bytes)) return '未知大小';

    const units = ['B', 'KB', 'MB', 'GB', 'TB'];
    let index = 0;
    let value = bytes;

    while (value >= 1024 && index < units.length - 1) {
      value /= 1024;
      index++;
    }

    return `${value.toFixed(2)} ${units[index]}`;
  };

  const formatDate = (dateString) => {
    if (!dateString) return '未知时间';
    try {
      return new Date(dateString).toLocaleString('zh-CN');
    } catch (err) {
      return '未知时间';
    }
  };

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Spin size="large" />
        <div style={{ marginTop: 16 }}>
          <Text>正在加载所有种子列表...</Text>
        </div>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ textAlign: 'center', padding: '50px' }}>
        <Text type="danger">加载失败: {error}</Text>
        <div style={{ marginTop: 16 }}>
          <Button onClick={loadAllTorrents}>重新加载</Button>
        </div>
      </div>
    );
  }

  return (
    <div style={{ padding: '24px' }}>
      <div style={{ marginBottom: 24 }}>
        <Title level={2}>所有上传的种子</Title>
        <Text type="secondary">
          通过 OSS 接口获取平台上所有用户上传的种子列表
        </Text>

        <Row gutter={16} style={{ marginTop: 16 }}>
          <Col span={6}>
            <Card>
              <Statistic title="总种子数" value={torrentsList.length} />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="总下载量"
                value={torrentsList.reduce((sum, t) => sum + (t.download || 0), 0)}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="总做种数"
                value={torrentsList.reduce((sum, t) => sum + (t.seeder || 0), 0)}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="总点赞数"
                value={torrentsList.reduce((sum, t) => sum + (t.upvote || 0), 0)}
              />
            </Card>
          </Col>
        </Row>
      </div>

      <Button
        onClick={loadAllTorrents}
        style={{ marginBottom: 16 }}
        loading={loading}
      >
        刷新列表
      </Button>

      <List
        dataSource={torrentsList}
        renderItem={(torrent) => (
          <List.Item key={torrent.id}>
            <Card
              style={{ width: '100%' }}
              actions={[
                <Button
                  key="download"
                  type="primary"
                  icon={<DownloadOutlined />}
                  onClick={() => handleDownload(torrent)}
                >
                  下载
                </Button>
              ]}
            >
              <Card.Meta
                title={
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                    <Text strong>{torrent.name || '未命名种子'}</Text>
                    <Tag color="blue">{torrent.classification || '未分类'}</Tag>
                  </div>
                }
                description={
                  <div>
                    <div style={{ marginBottom: 8 }}>
                      <Text>{torrent.comment || '暂无描述'}</Text>
                    </div>

                    <Space wrap>
                      <Space>
                        <UserOutlined />
                        <Text>{torrent.uploader || '匿名'}</Text>
                      </Space>

                      <Space>
                        <ClockCircleOutlined />
                        <Text>{formatDate(torrent.fileTimestamps)}</Text>
                      </Space>

                      <Space>
                        <DatabaseOutlined />
                        <Text>{formatFileSize(torrent.size)}</Text>
                      </Space>

                      <Space>
                        <ArrowUpOutlined />
                        <Text>{torrent.seeder || 0} 做种</Text>
                      </Space>

                      <Space>
                        <DownloadOutlined />
                        <Text>{torrent.download || 0} 下载</Text>
                      </Space>

                      <Space>
                        <LikeOutlined />
                        <Text>{torrent.upvote || 0} 点赞</Text>
                      </Space>

                      <Space>
                        <EyeOutlined />
                        <Text>{torrent.watchs || 0} 浏览</Text>
                      </Space>
                    </Space>

                    {torrent.hash && (
                      <div style={{ marginTop: 8 }}>
                        <Text code style={{ fontSize: '12px' }}>
                          Hash: {torrent.hash.substring(0, 16)}...
                        </Text>
                      </div>
                    )}
                  </div>
                }
              />
            </Card>
          </List.Item>
        )}
      />

      {torrentsList.length === 0 && !loading && (
        <div style={{ textAlign: 'center', padding: '50px' }}>
          <Text type="secondary">暂无种子数据</Text>
        </div>
      )}
    </div>
  );
};

export default AllTorrents; 